package com.jiguang.Electricvehicle;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.bumptech.glide.util.Util;


import java.io.File;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

/**
 * Created by codeest on 2016/8/2.
 */
public class ImageLoader {

    static DrawableCrossFadeFactory drawableCrossFadeFactory = new DrawableCrossFadeFactory.Builder(500).setCrossFadeEnabled(true).build();

    private ImageLoader() {
    }


    public static void load(Context context, String url, ImageView iv) {
        if (TextUtils.isEmpty(url)) {
            loadWithError(context, "", iv, R.mipmap.ic_launcher);
            return;
        }
        if (!isValidContextForGlide(context)) {
            return;
        }
        if (url.contains("gif") || url.contains("GIF")) {
            loadGif(context, url, iv);
        } else {
            if (Util.isOnMainThread()) {
                Glide.with(context)
                        .load(url)
                        .dontAnimate()
                        .diskCacheStrategy(DiskCacheStrategy.DATA)
                        .into(iv);
            }
        }
    }

    public static void loadWithError(Context context, String url, ImageView iv, @DrawableRes int errorId) {
        if (!TextUtils.isEmpty(url) && (url.contains("gif") || url.contains("GIF"))) {
            loadGif(context, url, iv);
            return;
        }


        if (Util.isOnMainThread() && isValidContextForGlide(context)) {
            Glide.with(context)
                    .load(url)
                    .error(errorId)
                    .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                    .diskCacheStrategy(DiskCacheStrategy.DATA)
                    .into(iv);
        }

    }

    public static void loadWithErrorAndPlaceHolder(Context context, String url, ImageView iv, @DrawableRes int errorId,
                                                   @DrawableRes int placeHolder) {
        if (Util.isOnMainThread() && isValidContextForGlide(context)) {
            Glide.with(context)
                    .load(url)
                    .error(errorId)
                    .placeholder(placeHolder)
                    .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                    .diskCacheStrategy(DiskCacheStrategy.DATA)
                    .into(iv);
        }

    }


    public static void load(Context context, int resId, ImageView iv) {
        if (Util.isOnMainThread() && isValidContextForGlide(context)) {
            Glide.with(context)
                    .load(resId)
                    .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                    .diskCacheStrategy(DiskCacheStrategy.DATA)
                    .into(iv);
        }

    }

    public static void loadGif(Context context, int resId, ImageView iv) {
        if (!isValidContextForGlide(context)) {
            return;
        }
        Glide.with(context)
                .load(resId)
//                .asGif()
                .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                .diskCacheStrategy(DiskCacheStrategy.DATA)
                .into(iv);
    }

    public static void loadGif(Context context, int resId, ImageView iv, int radius) {
        if (!isValidContextForGlide(context)) {
            return;
        }
        Glide.with(context)
                .load(resId)
//                .asGif()
                .apply(new RequestOptions()
                        .transforms(new RoundedCorners(radius)
                        ))
                .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                .diskCacheStrategy(DiskCacheStrategy.DATA)
                .into(iv);

    }

    public static void loadGif(Context context, String url, ImageView iv) {
        if (Util.isOnMainThread() && isValidContextForGlide(context)) {
            Glide.with(context)
                    .load(url)
                    .skipMemoryCache(false)
                    .centerCrop()
                    .into(iv);
        }
    }

    public static void loadGif(Context context, String url, ImageView iv, RequestListener requestListener) {
        if (Util.isOnMainThread() && isValidContextForGlide(context)) {
            Glide.with(context)
                    .load(url)
                    .skipMemoryCache(false)
                    .centerCrop()
                    .listener(requestListener)
                    .into(iv);
        }
    }

    public static void loadGifWithRadius(Context context, String url, ImageView iv, int radius) {
        if (Util.isOnMainThread() && isValidContextForGlide(context)) {
            Glide.with(context)
                    .load(url)
                    .apply(new RequestOptions()
                            .transform(new CenterCrop(), new RoundedCorners(radius)
                            ))
                    .skipMemoryCache(false)
                    .into(iv);
        }
    }

    public static void load(Context context, String url, ImageView iv, RequestListener requestListener) {
        if (!TextUtils.isEmpty(url) && (url.contains("gif") || url.contains("GIF"))) {
            loadGif(context, url, iv, requestListener);
            return;
        }
        if (!isValidContextForGlide(context)) {
            return;
        }
        if (Util.isOnMainThread()) {
            Glide.with(context)
                    .load(url)
                    .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                    .diskCacheStrategy(DiskCacheStrategy.DATA)
                    .listener(requestListener)
                    .into(iv);
        }
    }

    public static void load(Context context, String url, ImageView iv, @DrawableRes int placeholder) {
        load(context, url, iv, placeholder, false);
    }

    /**
     * 加载圆形图片
     *
     * @param context
     * @param url
     * @param imageView
     * @param error
     */
    public static void loadCircle(Context context, String url, ImageView imageView, int error) {
        if (!isValidContextForGlide(context)) {
            return;
        }
        Glide.with(context)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .error(error)
                .placeholder(R.mipmap.icon_bike)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(imageView);
    }

    /**
     * 加载圆形图片
     *
     * @param context
     * @param url
     * @param imageView
     * @param error
     */
    public static void loadCircle(Context context, String url, ImageView imageView, int error, int placeHolder) {
        if (!isValidContextForGlide(context)) {
            return;
        }
        Glide.with(context)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .error(error)
                .placeholder(placeHolder)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(imageView);
    }

    /**
     * 首页车标特殊处理
     *
     * @param context
     * @param url
     */
    public static void loadCircleForCarLogo(Context context, String url, int defaultDrawableId, int errorDrawableId, int plDrawableId, ImageView imageView) {
        if (!isValidContextForGlide(context)) {
            return;
        }
        RequestBuilder<Drawable> requestBuilder;
        if (TextUtils.isEmpty(url)) {
            requestBuilder = Glide.with(context).load(defaultDrawableId);
        } else {
            requestBuilder = Glide.with(context).load(url);
        }

        requestBuilder.placeholder(plDrawableId)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .error(errorDrawableId)
                .into(imageView);

    }

    public static void load(Context context, String url, ImageView iv, @DrawableRes int placeholder, boolean roundCorner) {
        //使用Glide加载圆形ImageView(如头像)时，不要使用占位图
        if (!isValidContextForGlide(context)) {
            return;
        }
        if (roundCorner) {
            Glide.with(context)
                    .load(url)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .error(R.mipmap.icon_bike)
                    .placeholder(placeholder)
                    .transform(new CircleCrop())
                    .into(iv);
        } else {
            Glide.with(context)
                    .load(url)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .error(R.mipmap.icon_bike)
                    .placeholder(placeholder)
                    .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                    .into(iv);
        }
    }

    public static void loadFitXY(Context context, String url, ImageView iv, @DrawableRes int placeholder,
                                 boolean roundCorner, int radius) { //使用Glide加载圆角图片
        if (!isValidContextForGlide(context)) {
            return;
        }
        if (roundCorner) {
            Glide.with(context)
                    .load(url)
                    .apply(new RequestOptions()
                            .transforms(new RoundedCorners(radius)
                            ))
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                    .error(R.mipmap.icon_bike)
                    .placeholder(placeholder)
//                    .transform(new CircleCrop())
                    .into(iv);
        } else {
            Glide.with(context)
                    .load(url)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .error(R.mipmap.icon_bike)
                    .placeholder(placeholder)
                    .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                    .into(iv);
        }
    }

    public static void load(Context context, String url, ImageView iv, @DrawableRes int placeholder,
                            @DrawableRes int errorId) { //使用Glide加载圆形ImageView(如头像)时，不要使用占位图
            if (Util.isOnMainThread() && isValidContextForGlide(context)) {
                Glide.with(context)
                        .load(url)
                        .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                        .diskCacheStrategy(DiskCacheStrategy.DATA)
                        .placeholder(placeholder)
                        .error(errorId)
                        .into(iv);
            }

    }

    //加载本地图片（不要用绝对路径）
    public static void loadUri(Activity activity, String url, ImageView iv, boolean isCircle) {
        if (!isValidContextForGlide(activity)) {
            return;
        }
        if (isCircle) {
            Glide.with(activity)
                    .load(Uri.fromFile(new File(url)))
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .transform(new CircleCrop())
                    .into(iv);
        } else {
            Glide.with(activity).load(Uri.fromFile(new File(url))).into(iv);
        }
    }

    public static void load(Activity activity, String url, ImageView iv) {
        if (!isValidContextForGlide(activity)) {
            return;
        }
        if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
            Glide.with(activity)
                    .load(url)
                    .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                    .diskCacheStrategy(DiskCacheStrategy.DATA)
                    .into(iv);
        } else {
            if (Util.isOnMainThread()) {
                Glide.with(activity)
                        .load(url)
                        .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
                        .diskCacheStrategy(DiskCacheStrategy.DATA)
                        .into(iv);
            }
        }
    }
    
    /**
     * 加载圆形图片
     *
     * @param context
     * @param view
     * @param url
     */
    public static void setCirclePicture(Context context, ImageView view, String url) {
        if (!isValidContextForGlide(context)) {
            return;
        }
        Glide.with(context)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .error(R.mipmap.icon_bike)
                .placeholder(R.mipmap.icon_bike)
                .transform(new CircleCrop())
                .into(view);
    }

    /**
     * 加载圆角图片 可配置圆角大小
     */
    public static void loadRoundCorner(Context context, String url, ImageView iv, int radius, int defaultImage) {
        loadFitXY(context, url, iv, defaultImage, true, radius);
    }


    public static File downloadOnly(Context context, String imgUrl) {
        if (isValidContextForGlide(context)) {
            try {
                return Glide.with(context).load(imgUrl).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    public static boolean isValidContextForGlide(Context context) {
        if (context == null) {
            return false;
        }
        if (context instanceof Activity) {
            final Activity activity = (Activity) context;
            if (activity.isDestroyed() || activity.isFinishing()) {
                return false;
            }
        }
        return true;
    }

}
